package com.rockxin.cat.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.rockxin.cat.R;
import com.rockxin.cat.activity.BidDetailsActivity;
import com.rockxin.cat.activity.TargetFilterActivity;
import com.rockxin.cat.adapter.TargetListAdapter;
import com.rockxin.cat.base.BaseFragment;
import com.rockxin.cat.bean.UseBean;
import com.rockxin.cat.event.TargetFilterEvent;
import com.rockxin.cat.network.CatNetWork;
import com.rockxin.cat.network.HttpResult;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Subscriber;

/**
 * <b>类名称：    MoneyFragment             <br/>
 * <b>类描述：                        <br/>
 * <b>创建人：    Lans               <br/>
 * <b>创建时间：  2018/3/1 13:11     <br/>
 * <b>修改人：                        <br/>
 * <b>修改时间：                      <br/>
 * <b>修改备注：                      <br/>
 *
 * @version 1.0.0 <br/>
 */
public class MoneyFragment extends BaseFragment {
    @BindView(R.id.back_img)
    ImageView backImg;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.right_img)
    ImageView rightImg;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.recyler_view)
    RecyclerView recylerView;

    private Unbinder unbinder;

    private List<UseBean> mList;
    private TargetListAdapter mAdapter;

    /**
     * @param p           当前页数
     * @param level       1(HR),2(E),3(D),4(C),5(B),6(A),7(AA)
     * @param deal_status 借款状态:19(未开始),1(进行中),2(满标),3(流标),4(还款中),5(已还清)
     * @param interest    回馈利率:10(10%以上),12(12%以上),15(15%以上),18(18%以上)
     * @param lefttime    剩余时间:1(1天以内),3(3天以内),6(6天以内),9(9天以内),12(12天以内)
     * @param is_company  借款用户:1(个人借款),2(企业借款)
     * @param months_type 借款期限:1(3个月以内),2(3-6个月),3(6-9个月),4(9-12个月),5(12个月以上)
     */
    private String level, deal_status, interest, lefttime, is_company, months_type;
    private int pageNum = 1;

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public static MoneyFragment newInstance() {
        Bundle args = new Bundle();
        MoneyFragment fragment = new MoneyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View mView = inflater.inflate(R.layout.fragment_money, container, false);
        //返回一个Unbinder值（进行解绑），注意这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, mView);
        initView();
        initRecyclerView();
        setListener();
        getData();
        EventBus.getDefault().register(this);
        return mView;
    }

    public void initView() {
        title.setText("标的列表");
        backImg.setVisibility(View.GONE);
        rightImg.setVisibility(View.VISIBLE);
        rightImg.setImageResource(R.mipmap.screen);
    }

    private void initRecyclerView() {
        mList = new ArrayList<>();

        mAdapter = new TargetListAdapter(R.layout.item_target_list, mList);
        recylerView.setAdapter(mAdapter);

        final LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recylerView.setLayoutManager(mLayoutManager);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                UseBean data = (UseBean) adapter.getItem(position);
                Logger.d("onItemClick---position:" + position + "    id:" + data.getId());
                Intent intent = new Intent(mContext, BidDetailsActivity.class);
                intent.putExtra("targetId", data.getId());
                startActivity(intent);
            }
        });
        refreshLayout.setRefreshHeader(new ClassicsHeader(mContext));//设置Header
        refreshLayout.setRefreshFooter(new ClassicsFooter(mContext));//设置Footer
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                mList.clear();
                getData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNum = pageNum + 1;
                getData();
            }
        });
    }

    private void setListener() {
        rightImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, TargetFilterActivity.class);
                startActivity(intent);
            }
        });
    }

    private void getData() {
        final CatNetWork catNetWork = new CatNetWork();
        catNetWork.loanlist(String.valueOf(pageNum), level, deal_status, interest, lefttime, is_company, months_type, new Subscriber<HttpResult<List<UseBean>>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (pageNum == 1) {
                    refreshLayout.finishRefresh();//传入false表示刷新失败
                } else {
                    refreshLayout.finishLoadMore();//传入false表示刷新失败
                }
            }

            @Override
            public void onNext(HttpResult<List<UseBean>> listHttpResult) {
                Logger.json(new Gson().toJson(listHttpResult));
                mList.addAll(listHttpResult.getData());
                mAdapter.notifyDataSetChanged();
                if (pageNum == 1) {
                    refreshLayout.finishRefresh();//传入false表示刷新失败
                } else {
                    refreshLayout.finishLoadMore();//传入false表示刷新失败
                }
            }
        });
    }

    @org.simple.eventbus.Subscriber(tag = "target_filter")
    public void getTargetFilterEvent(TargetFilterEvent targetFilterEvent) {
        Logger.d("============getTargetFilterEvent==============" + targetFilterEvent.getmProfitsId());
        interest = targetFilterEvent.getmProfitsId();
        months_type = targetFilterEvent.getmTermId();
        is_company = targetFilterEvent.getmBorrowerId();
        getData();
    }

}
